package com.google.code.jgchart;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.codec.EncoderException;
import org.apache.commons.codec.net.URLCodec;

public class Legend implements UrlQuery {

	private static final String DATA_LEGEND_PARAM = "chdl=";

	private static final String DATA_POSITION_PARAM = "chdlp=";

	private static final String POSTION_TOP = DATA_POSITION_PARAM + "t";

	private static final String POSTION_BOTTOM = DATA_POSITION_PARAM + "b";

	private static final String POSTION_RIGHT = DATA_POSITION_PARAM + "r";

	private static final String POSTION_LEFT = DATA_POSITION_PARAM + "l";

	private String urlCodec = "UTF-8";

	private List<String> legends = new ArrayList<String>();

	private String postion;

	public Legend() {
	}

	public Legend(String legend) {
		append(legend);
	}

	public Legend setUrlCodec(String urlCodec) {
		this.urlCodec = urlCodec;
		return this;
	}

	public Legend append(String legend) {
		if (legend == null) {
			throw new IllegalArgumentException("legend can't be null.");
		}
		legends.add(legend);
		return this;
	}

	public Legend setPostionTop(boolean yes) {
		if (yes) {
			postion = POSTION_TOP;
		}
		return this;
	}

	public Legend setPostionBottom(boolean yes) {
		if (yes) {
			postion = POSTION_BOTTOM;
		}
		return this;
	}

	public Legend setPostionRight(boolean yes) {
		if (yes) {
			postion = POSTION_RIGHT;
		}
		return this;
	}

	public Legend setPostionLeft(boolean yes) {
		if (yes) {
			postion = POSTION_LEFT;
		}
		return this;
	}

	public String[] getQuery() {
		if (legends.size() == 0) {
			return new String[] { "" };
		}
		StringBuilder sb = new StringBuilder();
		URLCodec codec = new URLCodec(urlCodec);
		try {
			sb.append(DATA_LEGEND_PARAM).append(codec.encode(legends.get(0)));
		} catch (EncoderException e) {
			throw genQueryEncoderException(legends.get(0), urlCodec, e);
		}
		for (int i = 1; i < legends.size(); i++) {
			try {
				sb.append("|").append(codec.encode(legends.get(i)));
			} catch (EncoderException e) {
				throw genQueryEncoderException(legends.get(i), urlCodec, e);
			}
		}

		if (postion != null) {
			return new String[] { sb.toString(), postion };
		}
		return new String[] { sb.toString() };
	}

	private QueryEncoderException genQueryEncoderException(String data,
			String codec, Throwable cause) {
		return new QueryEncoderException("legend(" + data + ") encode(" + codec
				+ ") error.", cause);
	}

}
